/* eslint-disable default-case */
/* eslint-disable array-callback-return */
import { routerRedux } from 'dva/router';
import { message } from 'antd';
import {
  getEmpList,
  delEmpList,
  getInsUnifyFlag,
  getIsSupplyScope,
  getAcountList,
  getGroupList,
  getSecAccoList,
  submit,
  getDetDetail,
  updateSubmit,
  getConfigDetail,
  getNmAreaCity,
  getUploadProgress,
  uploadFileService,
  getRespUserList,
} from '@/services/serviceconfig';
import * as service from '@/services/socket';
import { SocketActions, batchTaskFactory } from '@/models/socket';
import { delay } from '@/utils/dva';
// 非常重要属性
const namespace = 'serviceconfig';
const ModelAddEmp = {
  namespace,
  state: {
    insMergekindList: [], // 五险合一险种列表
    insNotMergekindList: [], // 五险不合一险种列表
    payWayList: [], // 缴费方式列表
    accountList: [], // 缴费账户列表
    secAccuList: [], // 工伤二级户列表
    custId: null,
    custConfName: null,
    remark: null,
    areaConfigId: 0, // 地区配置id
    tableId: 0, // 表格行标识
    detList: [],
    formFieldsValue: {},
    expandForm: false,
    pageData: {
      // 列表数据
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    configDetailData: {},
    batchQuery: {
      // 批量上传数据
      progressPercent: 0,
    },
    currentStep: 0,
    showProgress: false,
    progressPercent: 0,
    resultInfo: {
      // 结果数据必传
      batchName: '', // 任务名称
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batchNo: '', // 批次号
      errorUrl: '/csApi/custService/exportErrorExcel', // 下载错误信息地址
      errorParams: null, // 下载错误数据参数
    },
    valuesArr: ['custConfNo', 'custId', 'custConfId', 'primId'],
    respUserList: [],
    tempType: null,
  },
  effects: {
    // 获取首页列表数据**
    *fetchList({ payload }, { call, put }) {
      const response = yield call(getEmpList, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      yield put({
        type: 'getList',
        payload: {
          data: [],
          currentPage,
          pageSize,
        },
      });
      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
      }
    },
    // 删除单个列表数据**
    *delfetchList({ payload }, { call, put, select }) {
      const response = yield call(delEmpList, payload);
      if (response.success) {
        message.success('删除成功！');
        let values;
        yield select(state => {
          const currentPage = state.serviceconfig.pageData.pagination.current;
          const pageSizes = state.serviceconfig.pageData.pagination.pageSize;
          const pageArg = { currentPage, pageSize: pageSizes };
          values = {
            pageArg,
          };
        });
        yield put({
          type: 'fetchList',
          payload: values,
        });
      } else {
        message.warning(`${response.message || '删除失败！'}`);
      }
    },
    // 获取五险合不合一
    *fetchGetInsUnifyFlag({ payload }, { call, put, select }) {
      const response = yield call(getInsUnifyFlag, { areaId: payload.areaId });
      if (response.success) {
        const detList = yield select(state => state.serviceconfig.detList);
        const insMergekindList = yield select(state => state.serviceconfig.insMergekindList);
        const insNotMergekindList = yield select(state => state.serviceconfig.insNotMergekindList);
        detList.map(item => {
          const temp = item;
          if (item.id === payload.id) {
            temp.areaId = payload.areaId;
            temp.insSetFlag = (response.data && response.data.insUnifyFlag) || 1;
            if (item.confDetList.length) {
              item.confDetList.map(c => {
                const obj = c;
                obj.kindList = item.insSetFlag === 1 ? insMergekindList : insNotMergekindList;
              });
            }
          }
        });
        yield put({
          type: 'updateModelData',
          payload: { detList },
        });
      } else {
        message.warning(response.message || '获取五险合一：服务端错误');
      }
    },
    // 获取在不在供应商业务范围内
    *fetchIsSupplyScope(
      {
        payload: { areaId, insKinds, areaConfigId, key },
      },
      { call, put }
    ) {
      const response = yield call(getIsSupplyScope, { areaId, ass: insKinds[0] });
      if (response.success) {
        if (response.data) {
          yield put({
            type: 'updateAreaTableData',
            payload: {
              targetKey: 'isSupplyScope',
              value: response.data && response.data.rangeFlag,
              areaConfigId,
              key,
            },
          });
        } else {
          message.warning('该地区下该险种未维护供应商业务范围');
        }
      } else {
        message.warning(response.message || '获取供应商业务范围：服务端错误');
      }
    },
    // 获取缴费账户列表
    *fetchAcountList(
      {
        payload: { custId, areaId, insKinds, payWay, areaConfigId, key },
      },
      { call, put }
    ) {
      const response = yield call(getAcountList, { custId, areaId, insKinds, payWay });
      if (response.success) {
        if (response.data) {
          yield put({
            type: 'updateModelData',
            payload: {
              accountList: response.data,
            },
          });
          yield put({
            type: 'updateAreaTableData',
            payload: { targetKey: 'accountList', value: response.data, areaConfigId, key },
          });
          return response.data;
        }
        message.warning('该地区下该险种未维护缴费账户');
      } else {
        message.warning(response.message || '获取缴费账户列表：服务端错误');
      }
      return true;
    },

    // 获取政策组合列表
    *fetchGroupList(
      {
        payload: { custId, areaId, insKinds, payWay, pdId, areaConfigId, key },
      },
      { call, put }
    ) {
      const response = yield call(getGroupList, { custId, areaId, insKinds, payWay, pdId });
      if (response.success) {
        if (response.data) {
          yield put({
            type: 'updateModelData',
            payload: {
              groupList: response.data,
            },
          });
          yield put({
            type: 'updateAreaTableData',
            payload: { targetKey: 'groupList', value: response.data, areaConfigId, key },
          });
        } else {
          message.warning('该地区下该险种未维护政策组合');
        }
      } else {
        message.warning(response.message || '获取政策组合列表：服务端错误');
      }
    },
    // 获取工伤二级户列表
    *fetchSecAccoList(
      {
        payload: { custId, areaId, insKinds, payWay, areaConfigId, key },
      },
      { call, put }
    ) {
      const response = yield call(getSecAccoList, { custId, areaId, insKinds, payWay });
      if (response.success) {
        if (response.data) {
          response.data.map(item => {
            const temp = item;
            temp.value = item.accoId;
            temp.label = item.accoName;
            temp.isLeaf = (item.injSecAccoDtos && false) || true;
            if (item.injSecAccoDtos) {
              const children = [];
              item.injSecAccoDtos.map(c => {
                children.push({
                  value: c.injSecAccoId,
                  label: c.injSecAccoName,
                  isLeaf: true,
                });
              });
              temp.children = children;
            }
          });
          const secAccuList = response.data;
          let secAccuIntValue;
          if (
            secAccuList.length === 1 &&
            secAccuList[0].injSecAccoDtos &&
            secAccuList[0].injSecAccoDtos.length === 1
          ) {
            secAccuIntValue = [
              secAccuList[0].accoId,
              secAccuList[0].injSecAccoDtos[0].injSecAccoId,
            ];
            yield put({
              type: 'updateAreaTableData',
              payload: { targetKey: 'accoId', value: secAccuIntValue, areaConfigId, key },
            });
          }
          yield put({
            type: 'updateModelData',
            payload: {
              secAccuList,
            },
          });
          yield put({
            type: 'updateAreaTableData',
            payload: { targetKey: 'secAccuList', value: secAccuList, areaConfigId, key },
          });
        } else {
          message.warning('该地区下未维护社工伤二级户');
        }
      } else {
        message.warning(response.message || '获取工伤二级户列表：服务端错误');
      }
    },
    // 提交数据
    submit:[
      function*({ payload }, { call, put, select }) {
      let submitData = payload.values;
      const detList = yield select(state => state.serviceconfig.detList);
      submitData.custId = submitData.custId.key || submitData.custId;
      submitData.detList.map(item => {
        const obj = item;
        obj.areaId = item.areaId && item.areaId.key;
        detList.forEach(d => {
          if ((d.areaId.key || d.areaId) === item.areaId) {
            obj.insSetFlag = d.insSetFlag;
          }
        });
        if (Array.isArray(item.confDetList)) {
          obj.confDetList = item.confDetList.filter(c => c);
        } else {
          // eslint-disable-next-line compat/compat
          obj.confDetList = Object.values(item.confDetList);
        }
        item.confDetList.map(c => {
          const objs = c;
          if (Array.isArray(c.accoId)) {
            if (c.accoId.length) {
              objs.accoId = c.accoId[c.accoId.length - 1];
            } else {
              objs.accoId = null;
            }
          }
        });
      });
      submitData = payload.custConfId
        ? { ...submitData, custConfId: payload.custConfId }
        : submitData;
      const response = yield call(payload.custConfId ? updateSubmit : submit, submitData);
      if (response.success) {
        const state = {
          insMergekindList: [], // 五险合一险种列表
          insNotMergekindList: [], // 五险不合一险种列表
          payWayList: [], // 缴费方式列表
          accountList: [], // 缴费账户列表
          secAccuList: [], // 工伤二级户列表
          custId: null,
          custConfName: null,
          remark: null,
          areaConfigId: 0, // 地区配置id
          tableId: 0, // 表格行标识
          detList: [],
          custInfo: undefined,
        };
        yield put({
          type: 'updateModelData',
          payload: { ...state },
        });
        message.success(payload.custConfId ? '保存成功!' : '新增成功！');
        yield put(
          routerRedux.push({
            pathname: '/customservicemanage/serverconfig/index',
          })
        );
      } else {
        message.warning(`${response.message || '保存失败！'}`);
      }
    },
    { type:'throttle',ms:10000 }
  ],
    // 获取修改回显数据
    *fetchUpdateInfo({ payload }, { call, put, select }) {
      const response = yield call(getDetDetail, payload);
      const insMergekindList = yield select(state => state.serviceconfig.insMergekindList);
      const insNotMergekindList = yield select(state => state.serviceconfig.insNotMergekindList);
      if (response.success) {
        const custInfo = {
          key: response.data.custId,
          label:
            (response.data.suppName &&
              response.data.custName &&
              `${response.data.custName}(${response.data.suppName})`) ||
            `${response.data.custName}`,
        };
        if (response.data.detList && response.data.detList.length) {
          response.data.detList.map(item => {
            const temp = item;
            temp.id = item.areaId;
            temp.areaId = { key: item.areaId, label: item.areaName };
            if (item.confDetList && item.confDetList.length) {
              item.confDetList.map(c => {
                const cc = c;
                cc.id = item.id;
                cc.kindList = item.insSetFlag === 1 ? insMergekindList : insNotMergekindList;
                cc.key = c.custConfDetId;
                cc.kind = `${c.kind}`;
                cc.payWay = `${c.payWay}`;
                if (c.injSecAccoId) {
                  cc.isSecAccu = true;
                  cc.accoId = [c.accoId, c.injSecAccoId];
                }
              });
            }
          });
        }
        yield put({
          type: 'updateModelData',
          payload: { ...response.data, custInfo },
        });
        return response;
      }
      message.warning(`${response.message || '服务端错误！'}`);
      return true;
    },
    // 获取服务配置详情数据
    *getConfigDetail({ payload }, { call, put }) {
      const response = yield call(getConfigDetail, payload);
      if (response.success) {
        yield put({
          type: 'updateModelData',
          payload: {
            configDetailData: response.data,
          },
        });
      } else {
        message.warning(`${response.message || '获取服务配置数据：服务端错误！'}`);
      }
      return response;
    },
    // 查所有的市
    *getNmAreaCity({ payload }, { call }) {
      const response = yield call(getNmAreaCity, payload);
      return response;
    },
    // 获取上传进度数据
    *getUploadProgress({ payload, callback }, { call, put }) {
      const response = yield call(getUploadProgress, payload);
      if (response.success) {
        yield put({
          type: 'updateQuery',
          payload: { progressPercent: response.data.successProp },
        });
      }
      if (callback && typeof callback === 'function') {
        callback(response);
      }
    },
    // 上传文件:批量进度
    uploadFileWithProgress:[
      function*({ payload }, { call, put }) {
      try {
        const response = yield call(uploadFileService, payload);
        if (response.success) {
          yield put({
            type: 'setTempType',
            payload: { tempType: response.data && response.data.tempType },
          });
          // 不是100表示需要走队列
          if (response.data && response.data.successProp !== 100) {
            const { batchId } = response.data;
            const batchTask = batchTaskFactory(batchId, namespace, 'handleBatchTask');

            yield put.resolve({
              type: `socket/${SocketActions.subSocketChannel}`,
              payload: {
                batchTask,
              },
            });
            // 订阅成功后再触发进度条
            yield put({
              type: 'updateModelData',
              payload: { showProgress: true },
            });
          } else {
            yield put({
              type: 'handleBatchTask',
              payload: response.data,
            });
          }
        } else {
          message.warning(response.message || '上传文件错误：服务器端错误');
        }

        // 无需返回response对象
      } catch (e) {
        console.error(e);
      }
    },
    { type:'throttle',ms:10000 }
  ],
    *handleBatchTask({ payload }, { put, select }) {
      const state = yield select(s => s.serviceconfig);
      const { tempType } = state;
      let { showProgress, resultInfo, currentStep } = state;
      showProgress = true;
      if (payload.successProp >= 100) {
        resultInfo.errorParams = {
          batchId: payload.batchId,
          tempType,
        };
        resultInfo = { ...resultInfo, ...payload };
        currentStep += 1;
        showProgress = false;
        // 先更新进度
        yield put({
          type: 'updateBatchTask',
          payload: {
            progressPercent: payload.successProp,
            resultInfo,
          },
        });
        yield delay(3000);
        // 再更新状态
        yield put({
          type: 'updateBatchTask',
          payload: {
            currentStep,
            showProgress,
          },
        });
      } else {
        yield put({
          type: 'updateBatchTask',
          payload: { progressPercent: payload.successProp, resultInfo },
        });
      }
    },
    // 获取所属客服列表
    *fetchRespUserList({ payload }, { call, put }) {
      const response = yield call(getRespUserList, payload);
      yield put({
        type: 'updateModelData',
        payload: {
          respUserList: [],
        },
      });
      if (response.success && response.data) {
        yield put({
          type: 'updateModelData',
          payload: {
            respUserList: Array.isArray(response.data) ? response.data : [],
          },
        });
      } else {
        message.warning(response.message || '获取所属客服数据：服务端错误');
      }
    },
  },

  reducers: {
    // 获取列表
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        pageData: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },
    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 设置查询时保存的值
    updateTabListQuery(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 更新地区下表格数据源
    updateAreaTableData(
      state,
      {
        payload: { targetKey, value, areaConfigId, key },
      }
    ) {
      const { detList } = state;
      detList.map(item => {
        if (item.id === areaConfigId) {
          if (item.confDetList.length) {
            item.confDetList.map(c => {
              const temp = c;
              if (c.key === key) {
                temp[targetKey] = value;
              }
            });
          }
        }
      });
      return {
        ...state,
        ...detList,
      };
    },
    // 更新批量上传参数
    updateQuery(state, { payload }) {
      return {
        ...state,
        batchQuery: { ...state.batchQuery, ...payload },
      };
    },
    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    setTempType(state, { payload }) {
      return {
        ...state,
        tempType: payload.tempType,
      };
    },
    setCustInfo(state, { payload }) {
      return {
        ...state,
        custInfo: payload.custInfo,
      };
    },
    setCustId(state, { payload }) {
      return {
        ...state,
        custId: payload.custId,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      service.listen(async action => {
        // 判断是否自己命名空间的回调

        if (action.namespace === namespace) {
          switch (action.type) {
            case 'task':
              await dispatch({
                type: 'handleBatchTask',
                payload: action.data,
              });
              await dispatch({
                type: `socket/${SocketActions.handleUpdateBatchTask}`,
                payload: {
                  successProp: action.data.successProp,
                  batchId: action.data.batchId,
                },
              });
              // 全局保存
              dispatch({
                type: 'publicdata/updateBatchTaskData',
                payload: action.data,
              });
              break;
          }
        }
      }, namespace);
    },
  },
};

export default ModelAddEmp;
